<template>
  <Content :title="pageType == 'outbound' ? '出库' : '入库'">
    <view class="from-box" style="padding-bottom: 160rpx">
      <view class="content content-bottom">
        <u-form
          labelPosition="left"
          :model="model"
          labelWidth="80"
          labelAlign="left"
          :rules="rules"
          ref="uForm"
        >
			<u-form-item borderBottom label="RFID编码" prop="moldName">
			  <u-input
				label
				disabled
				v-model="RFIDCode"
				placeholder="请将模块放置感应区按侧边扫码键扫描"
				clearable
			  ></u-input>
			</u-form-item>
          <u-form-item borderBottom label="模具编码" prop="moldCode" required>
            <uni-data-select
              v-model="model.moldCode"
              :localdata="moldInfoList"
              showInput
              @inputChange="getMoldInfo"
              placeholder="请选择"
              @change="getMoldInfoChange"
            ></uni-data-select>
          </u-form-item>

          <u-form-item borderBottom label="模具名称" prop="moldName">
            <u-input
              label
              disabled
              v-model="model.moldName"
              placeholder="请填写模具名称"
              clearable
            ></u-input>
          </u-form-item>

          <u-form-item
            borderBottom
            label="功能位置"
            prop="functionalLocation"
            required
          >
            <MySelect
              cascader
              v-model="model.functionalLocation"
              :option="orgList"
              @change="orgListChange"
              placeholder="请选择"
            ></MySelect>
          </u-form-item>

          <u-form-item borderBottom label="库区" prop="reservoirArea" required>
            <uni-data-select
              v-model="model.reservoirArea"
              :localdata="kuquList"
              placeholder="请选择"
              @change="kuquChange"
            ></uni-data-select>
          </u-form-item>

          <u-form-item
            borderBottom
            label="库位"
            prop="warehouseLocation"
            required
          >
            <uni-data-select
              v-model="model.warehouseLocation"
              :localdata="kuweiList"
              placeholder="请选择"
            ></uni-data-select>
          </u-form-item>

          <template v-if="pageType == 'warehousing'">
            <u-form-item
              borderBottom
              label="入库类型"
              prop="receiptType"
              required
            >
              <uni-data-select
                v-model="model.receiptType"
                :localdata="receiptTypeList"
                placeholder="请选择"
              ></uni-data-select>
            </u-form-item>

            <u-form-item borderBottom label="入库事由" prop="reasonStorage">
              <u-textarea
                v-model="model.reasonStorage"
                placeholder="请填写入库事由"
              ></u-textarea>
            </u-form-item>
          </template>
          <template v-else>
            <u-form-item
              borderBottom
              label="出库类型"
              prop="outboundType"
              required
            >
              <uni-data-select
                v-model="model.outboundType"
                :localdata="outboundTypeList"
                placeholder="请选择"
              ></uni-data-select>
            </u-form-item>

            <u-form-item borderBottom label="出库事由" prop="reasonStorage">
              <u-textarea
                v-model="model.reasonStorage"
                placeholder="请填写出库事由"
              ></u-textarea>
            </u-form-item>
          </template>

          <u-form-item borderBottom label="备注" prop="remarks">
            <u-textarea
              v-model="model.remarks"
              placeholder="请填写备注"
            ></u-textarea>
          </u-form-item>

          <view class="btn-v">
            <view class="but-box">
              <u-button class="btn" text="取消" @click="close"></u-button>
              <u-button
                class="btn"
                type="primary"
                @click="submit"
                :loading="loading"
                text="确认"
              ></u-button>
            </view>
          </view>
        </u-form>
      </view>
    </view>
  </Content>
</template>

<script>
import Content from "@/components/content/index.vue";
import { getPageData, getUserInfo } from "@/store/user";
import fetch from "@/utils/fetch";
import { addApi, getMoldInfoList } from "@/api/moldManagement/moldInApply.js";
import {
  addApi as addApi1,
  getMoldInfoList as getMoldInfoList1,
} from "@/api/moldManagement/moldOutApply.js";
import {
		initScan,
		startScan,
		stopScan
	} from "@/utils/scan";
import recursion from "@/utils/recursion";
import { findOrgByToken, getDictData } from "@/api/index.js";
import MySelect from "@/components/mySelect.vue";
export default {
  props: {
    pageType: {
      type: String,
      default: "warehousing",
    },
    type: {
      type: String,
      default: "edit",
    },
  },
  options: {
    multipleSlots: true,
  },
  components: {
    Content,
    MySelect,
  },
 
  data() {
    return {
      userInfo: {},
      model: {
        moldCode: "",
        moldName: "",
        functionalLocation: [],
        mlocationCode: [],
        mlocation: "",
        reservoirArea: "",
        warehouseLocation: "",
        receiptType: "",
        reasonStorage: "",
        remarks: "",
        remark: "",
      },
	  RFIDCode:'',
      rules: {
        moldCode: {
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        functionalLocation: {
          type: "array",
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        reservoirArea: {
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        warehouseLocation: {
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        receiptType: {
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        outboundType: {
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
      },
      moldInfoList: [],
      receiptTypeList: [],
      outboundTypeList: [],
      orgList: [],
      loading: false,
      kuweiList: [],
      kuquList: [],
    };
  },
  onReady: function () {
    this.userInfo = getUserInfo();
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.rules);
  },
  mounted() {
    // 获取入库类型
    this.getDictList();
    this.getOrgList();
	// #ifdef APP-PLUS
	initScan(this.scanSuccess,'RFID');
	startScan();
	// #endif
  },
  async destroyed() {
  	// #ifdef APP-PLUS
  	console.log('结束了')
  	stopScan();
  	// #endif
  },
  methods: {
    async getMoldInfoChange(params) {
      if (!!!params) {
        this.model.moldName = "";
        return;
      }
      // this.model.moldName =
      //   this.moldInfoList.find((item) => item.moldCode == params).moldName ||
      //   "";
		const data = this.moldInfoList.find((item) => item.moldCode == params) || {};
		this.model.moldName = data.moldName;
		this.RFIDCode = data.rfidEncoding;
		if (data.functionalLocationName) {
			this.model.functionalLocation=data.functionalLocationName;
			await this.changeLocation(this.model.functionalLocation)
			this.model.reservoirArea=data.reservoirArea;

			await this.kuquChange(this.model.reservoirArea);
			this.model.warehouseLocation=data.warehouseLocation;
		}
    },
    async changeLocation(val) {
      this.locationCode = [];
      if (val && val.length) {
        this.locationCode = [val[val.length-1]];
      } else return;
      console.log(val);
      const res=await fetch("post", "/dms/moldStoragelocation/getFunctionalLocationList", {
        pageNum: 1,
        pageSize: 9999,
        mlocationCode: this.locationCode,
      })
	  // .then((res) => {
        this.kuquList = res.data.map((item) => {
          return {
            text: item.mreservoir,
            value: item.mreservoir,
          };
        });
   //    });
    },
    async kuquChange(val) {
      console.log(val);
      const res=await fetch("post", "/dms/moldStoragelocation/getFunctionalLocationList", {
        // pageNum: 1,
        // pageSize: 9999,
        mreservoir: val,
        mlocationCode: this.locationCode,
      })
	  this.kuweiList = res.data.map((item) => {
		 return {
		   text: item.mwarehouse,
		   value: item.mwarehouse,
		 };
	   });
	  // .then((res) => {
   //      this.kuweiList = res.data.records.map((item) => {
   //        return {
   //          text: item.mwarehouse,
   //          value: item.mwarehouse,
   //        };
   //      });
   //    });
    },
    getDictList() {
      if (this.pageType == "outbound") {
        getDictData("出库类型").then(({ data }) => {
          this.outboundTypeList =
            data?.map((item) => {
              return {
                ...item,
                text: item.value,
                value: item.value,
              };
            }) || [];
        });
      } else {
        getDictData("入库类型").then(({ data }) => {
          this.receiptTypeList =
            data?.map((item) => {
              return {
                ...item,
                text: item.value,
                value: item.value,
              };
            }) || [];
        });
      }
    },
    async getMoldInfo(query) {
      if (!query) return;
      const fun =
        this.pageType == "outbound" ? getMoldInfoList1 : getMoldInfoList;
      const res=await fun({ moldCode: query });
	  console.log(JSON.stringify(res.data.records),12312)
	  // .then(({ data }) => {
		if(res.data.records.length==0){
		  uni.$emit("openToast", {
		    type: "error",
		    title: `该模具已${this.outbound?'出库':'入库'}`,
		  });
		}
		this.moldInfoList =
		res.data.records?.map((item) => {
		  return {
		    ...item,
		    text: item.moldCode,
		    value: item.moldCode,
		  };
		}) || [];
        
   //    });
    },
    orgListChange(val, names) {
      this.model.mlocationCode = val;
      this.model.mlocation = names.join("/");
      this.changeLocation(this.model.functionalLocation);
    },
    getOrgList() {
      let params = {
        level: 0,
      };
      findOrgByToken(params).then(({ data }) => {
        const obj = {
          label: "name",
          text: "name",
          value: "code",
          children: "children",
        };
        this.orgList = recursion.convertTree(data, obj);
      });
    },
    close() {
      uni.navigateBack({
        delta: 1,
      });
    },
	async scanSuccess(code) {
		console.log('红外线扫码的结果', code);
		this.RFIDCode=code;
		const res=await fetch("get", "/dms/moldinfo/queryRFIDList",null, {
		  rfidEncoding: code,
		})
		if (res.data && res.data.length!==0) {
			const moldCode=res.data[0].moldCode || '';
			await this.getMoldInfo(moldCode)
			await this.getMoldInfoChange(moldCode);
			this.model.moldCode=moldCode
		}else {
			this.$set(this,'model',{})
		
			this.$refs.uForm.resetFields()
		}
		
	},
    submit() {
      this.$refs.uForm.validate().then((valid) => {
        if (valid) {
          this.loading = true;
          let applicant = getUserInfo().realname;
          const fun = this.pageType == "outbound" ? addApi1 : addApi;
          fun({ ...this.model, applicant }).then((res) => {
            this.loading = false;
            this.model = {};
            uni.$emit("openToast", {
              type: "success",
              title: res.msg,
            });
          });
        } else {
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.from-box {
  padding: 20rpx;
  background-color: #f7f7f7;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column;

  /deep/ .u-form-item__body__left__content__label {
    margin-left: 20rpx;
  }

  // /deep/ .uni-select {
  //     border: none;
  //     border-bottom: none;
  //     line-height: 26px;
  //     height: 24px !important;
  //     padding-left: 0;
  // }

  /deep/ .uni-select__input-placeholder {
    color: #cbc9cc !important;
    font-size: 15px !important;
  }
}

.content {
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  border-radius: 5px;
  box-shadow: 0 12rpx 18rpx -6rpx rgba(0, 0, 0, 0.2);
}

.content-bottom {
  flex: 1;
}
</style>
